package com.jia.together.config;

import com.jia.together.entity.Permission;
import com.jia.together.filter.JWTLoginFilter;
import com.jia.together.filter.JWTValidationFilter;
import com.jia.together.filter.WebSecurityCorsFilter;
import com.jia.together.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;

import java.util.Arrays;
import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PermissionService permissionService;

    // 使用自定义的
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.GET,
                "/v2/**", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html/**","/webjars/**", "/front/**")
                .antMatchers(HttpMethod.POST,"/front/**","/auth/login","/user/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 放行的路径
        http.authorizeRequests()
                .antMatchers("/**","/auth/login","/error/**").permitAll();
        // 添加自定义登录过滤器
        http
                //.addFilterBefore(new WebSecurityCorsFilter(), ChannelProcessingFilter.class) // 保证跨域的过滤器首先触发
                //.addFilter(new JWTValidationFilter(authenticationManager()))
                .addFilter(new JWTLoginFilter(authenticationManager()))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); //剔除session

        List<Permission> permissionList = permissionService.list();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry = http.authorizeRequests();
        // 添加方向的路径和需要的权限
        permissionList.forEach(permission->{
            if (!StringUtils.isEmpty(permission.getPermissionValue()) && !StringUtils.isEmpty(permission.getPath())){
                expressionInterceptUrlRegistry
                        .antMatchers(permission.getPath())
                        .hasAnyAuthority(permission.getPermissionValue());
            }
        });
        // 拦截其他
        http.authorizeRequests()
                .requestMatchers( CorsUtils::isPreFlightRequest ).permitAll()
                .anyRequest().authenticated();
        // 禁用CSRF防护 开启跨域
        http.csrf().disable();
    }


    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

